<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';


    if(!IsValidSession())
    {
        header('Location: login.php?page=add-new-user');
        exit();
    }
    else
    {
        RefreshSession();
    }
	
	$user = GetCurrentUserAccessLevel();
	
    //Check user access
    if($user != $DIRECTOR && $user != $ADMIN)
    {
        header('Location: login.php?page=add-new-user&error=To access to the create new user page, please log in as a director or admin&logout=1');
        exit();
    }

    if($_POST['firstName'] == "" || $_POST['roles'] == "" ||
	$_POST['lastName'] == "" || $_POST['userName'] == "" ||
	$_POST['password'] == "" || $_POST['confirmPassword'] == "")
    {
	$_SESSION['login_error'] = 'All fields are required. Please try again.';
	header("Location: add-new-user.php");
	exit();
    }

    if($_POST['password'] != $_POST['confirmPassword'])
    {
	$_SESSION['login_error'] = 'Passwords don\'t match. Please re-enter again.';
	header("Location: add-new-user.php");
	exit();
    }
    $link = connect_db();
    $query = "SELECT `UserId` FROM `User` WHERE `UserId` LIKE 'EM%' ORDER BY  `User`.`UserId` DESC;";
    $result = mysql_query($query,$link);
    $last_user = mysql_fetch_array($result,MYSQL_BOTH);
    $last_user = substr($last_user['UserId'],2);
    $new_user = str_pad($last_user+1,6,'0',STR_PAD_LEFT);

    $hash = gen_passwd_hash($_POST['password']);

    $query = "INSERT INTO `User` (`UserId`,
                                  `UserName`,
                                  `Password`,
                                  `PrivilegeLevel`,
                                  `FirstName`,
                                  `MiddleName`,
                                  `LastName`,
                                  `EmailAddress`,
                                  `Active`) VALUES
                                  ('EM".$new_user."',
                                   '".$_POST['userName']."',
                                   '".$hash."',
                                   '".$_POST['roles']."',
                                   '".$_POST['firstName']."',
                                   '".$_POST['middleName']."',
                                   '".$_POST['lastName']."',
                                   '".$_POST['emailAddress']."',
                                   '1');";
	
    masterpage("Add New User");
	
	try
	{
    $result = mysql_query($query,$link);
	} catch(Exception $exception)
	{
		echo '<table>';
		echo '<tr><td>'.$exception->getMessage().'</td></tr>';
		echo '</table>';
	}
    addLogEntry('User', 'Added user: EM'.$new_user);

    echo '<table>';
    if(!$result) 
    {
        echo '<tr><th class="tableTitle">User Not Added</th></tr>';
        echo '<tr><td align="center"><a href="index.php">To try again click here</a></td></tr>';
        echo '<tr><td>Error:<p>'.mysql_error().'</td></tr>';
    }
    else
    {
        echo '<tr><th class="tableTitle">User Successfully Added</th></tr>';
        echo '<tr><td align="center"><a href="index.php">Return to Homepage</a></td></tr>';
    }
    
    echo '</table>';

    endmasterpage();
?>
